package com.education.platform.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.education.platform.common.Result;
import com.education.platform.dto.conversation.ConversationCreateDTO;
import com.education.platform.entity.Conversation;
import com.education.platform.service.ConversationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 会话控制器
 *
 * @author education-platform
 * @since 2024-10-07
 */
@Tag(name = "会话管理", description = "会话管理相关接口")
@RestController
@RequestMapping("/api/conversation")
@RequiredArgsConstructor
public class ConversationController {

    private final ConversationService conversationService;

    @Operation(summary = "创建私聊会话", description = "创建或获取私聊会话")
    @PostMapping("/private")
    @SaCheckLogin
    public Result<Conversation> createPrivateConversation(@RequestParam Long targetUserId) {
        Long currentUserId = StpUtil.getLoginIdAsLong();
        String conversationId = conversationService.createPrivateConversation(currentUserId, targetUserId);
        // 返回完整的会话对象
        Conversation conversation = conversationService.getConversationById(conversationId);
        return Result.success(conversation);
    }

    @Operation(summary = "创建群聊会话", description = "创建群聊会话")
    @PostMapping("/group")
    @SaCheckLogin
    public Result<String> createGroupConversation(@Validated @RequestBody ConversationCreateDTO conversationCreateDTO) {
        String conversationId = conversationService.createGroupConversation(
                conversationCreateDTO.getName(),
                conversationCreateDTO.getAvatar(),
                conversationCreateDTO.getUserIds()
        );
        return Result.success(conversationId);
    }

    @Operation(summary = "获取会话详情", description = "根据ID获取会话详细信息（包含对方用户信息）")
    @GetMapping("/{id}")
    @SaCheckLogin
    public Result<Conversation> getConversationDetail(@PathVariable String id) {
        Long currentUserId = StpUtil.getLoginIdAsLong();
        Conversation conversation = conversationService.getConversationDetailWithUserInfo(id, currentUserId);
        return Result.success(conversation);
    }

    @Operation(summary = "分页查询会话列表", description = "分页查询当前用户的会话列表")
    @GetMapping("/page")
    @SaCheckLogin
    public Result<IPage<Conversation>> getConversationPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "20") Integer size) {
        Long userId = StpUtil.getLoginIdAsLong();
        Page<Conversation> page = new Page<>(current, size);
        IPage<Conversation> result = conversationService.getUserConversationPage(page, userId);
        return Result.success(result);
    }

    @Operation(summary = "获取会话列表", description = "获取当前用户的会话列表")
    @GetMapping("/list")
    @SaCheckLogin
    public Result<List<Conversation>> getConversationList() {
        Long userId = StpUtil.getLoginIdAsLong();
        List<Conversation> conversations = conversationService.getUserConversations(userId);
        return Result.success(conversations);
    }

    @Operation(summary = "获取私聊会话", description = "获取与指定用户的私聊会话")
    @GetMapping("/private/{targetUserId}")
    @SaCheckLogin
    public Result<Conversation> getPrivateConversation(@PathVariable Long targetUserId) {
        Long currentUserId = StpUtil.getLoginIdAsLong();
        Conversation conversation = conversationService.getPrivateConversation(currentUserId, targetUserId);
        return Result.success(conversation);
    }

    @Operation(summary = "更新会话信息", description = "更新会话名称和头像")
    @PutMapping("/{id}")
    @SaCheckLogin
    public Result<Void> updateConversation(
            @PathVariable String id,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String avatar) {
        conversationService.updateConversation(id, name, avatar);
        return Result.success();
    }

    @Operation(summary = "添加会话参与者", description = "添加用户到会话")
    @PostMapping("/{id}/participants")
    @SaCheckLogin
    public Result<Void> addParticipant(@PathVariable String id, @RequestParam Long userId) {
        conversationService.addParticipant(id, userId);
        return Result.success();
    }

    @Operation(summary = "移除会话参与者", description = "从会话中移除用户")
    @DeleteMapping("/{id}/participants/{userId}")
    @SaCheckLogin
    public Result<Void> removeParticipant(@PathVariable String id, @PathVariable Long userId) {
        conversationService.removeParticipant(id, userId);
        return Result.success();
    }

    @Operation(summary = "获取会话参与者", description = "获取会话参与者列表")
    @GetMapping("/{id}/participants")
    @SaCheckLogin
    public Result<List<Long>> getParticipants(@PathVariable String id) {
        List<Long> participants = conversationService.getParticipants(id);
        return Result.success(participants);
    }

    @Operation(summary = "检查参与者权限", description = "检查当前用户是否为会话参与者")
    @GetMapping("/{id}/check-participant")
    @SaCheckLogin
    public Result<Boolean> checkParticipant(@PathVariable String id) {
        Long userId = StpUtil.getLoginIdAsLong();
        Boolean isParticipant = conversationService.isParticipant(id, userId);
        return Result.success(isParticipant);
    }

    @Operation(summary = "删除会话", description = "删除会话")
    @DeleteMapping("/{id}")
    @SaCheckLogin
    public Result<Void> deleteConversation(@PathVariable String id) {
        Long userId = StpUtil.getLoginIdAsLong();
        conversationService.deleteConversation(id, userId);
        return Result.success();
    }
}
